<?php
namespace app\common\service;

use app\common\helper\BaseHelper;
use app\common\helper\CoursePosterHelper;
use app\common\helper\ExcelHelper;
use app\common\model\Course;
use app\common\util\Sms;
use app\common\util\Util;
use think\Db;
use think\Model;
use think\Request;

class CourseService extends BaseService
{

    /**
     * @param $sid
     * @param $uid
     * @param $type
     * @param $p
     * 获取某学员正式课程列表
     */
    public function getStudentOwnCourseList($sid, $uid, $type, $p){

        $condition = [];
        $cur_time = time();

        if($type == 'unstart'){
            //未开始
            $condition['c.schooltime'] = ['>',$cur_time];
        } elseif ($type == 'finished'){
            //已结束
            $condition['c.schoolovertime'] = ['<',$cur_time];
        } elseif ($type == 'signed'){
            //已签到
            $condition['sign_status'] = 1;
        }

        $condition['cs.uid'] = $uid;
        //正式学员
        $condition['cs.formal_status'] = 1;
        $condition['cs.ourclass_status'] = 1;

        $field = 'cs.courseid,cs.uid,cs.attend_status,cs.sign_status,cs.formal_status as student_status,cs.ourclass_status,
                 c.sid,c.name,c.speaker,c.schooltime,c.schoolovertime,c.description,c.content,c.pic,c.status as course_status';

        $course_list = db()->name('course_students')
                        ->alias('cs')
                        ->field($field)
                        ->join('course c', 'c.courseid = cs.courseid')
                        ->where($condition)
                        ->limit(($p-1) * $this->pageSize , $this->pageSize)
                        ->select();

        if($course_list){
            foreach ($course_list as $k => $v){
                $course_list[$k]['schooltime'] = date('Y-m-d H:i:s',$v['schooltime']);
                $course_list[$k]['schoolovertime'] = date('Y-m-d H:i:s',$v['schoolovertime']);

                $content = json_decode(htmlspecialchars_decode($v['content']), 1);
                $course_list[$k]['content'] = !empty($content['PModules'][0]['content']['fulltext']) ? $content['PModules'][0]['content']['fulltext'] : '';

                $course_list[$k]['speaker'] = json_decode($v['speaker']);
            }
        }

        return $course_list;
    }

    /**
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return array|bool
     * 获取某学员课程详情
     */
    public function getStudentCourseDetail($sid ,$uid, $course_id){
        //获取课程详情
        $course_detail = $this->getCourseDetail($course_id);

        if($course_detail === false){
            return false;
        }
        $course_detail['schooltime'] = date('Y-m-d H:i:s',$course_detail['schooltime']);
        $course_detail['schoolovertime'] = date('Y-m-d H:i:s',$course_detail['schoolovertime']);
        //判断审核状态
        $listening_where = [
            'uid' => $uid,
            'courseid' => $course_id,
            'status' => ['<>', 2]
        ];
        $listening = db('course_listening')->where($listening_where)->order('courseid DESC')->find();
        if($listening){
            if($listening['status'] == 0){
                //待审核
                $course_detail['listening_status'] = 1;
            } elseif ($listening['status'] == 1){
                //已通过
                $course_detail['listening_status'] = 2;
            }
        } else {
            //可申请
            $course_detail['listening_status'] = 0;
        }

        //查询该学生是否参加此课程
        $attend_status = db('course_students')->where(['courseid' => $course_id, 'uid' => $uid])->value('attend_status');
        $course_detail['attend_status'] = $attend_status ?? 0;

        return $course_detail;
    }

    /**
     * @param $course_id
     * @return array|bool
     * 获取课程详情
     */
    public function getCourseDetail($course_id, $filed = '*'){
        $course_detail = db('course')->field($filed)->where(['courseid' => $course_id, 'course_status' => ['in', [0,1]]])->find();

        if(empty($course_detail)){
            return false;
        }
        $content = $course_detail['content'];
        if(substr($content,0,1) == "{")
        {
            $content = json_decode(htmlspecialchars_decode($content), true);

            $content = ($content['PModules'][0]['content']['fulltext']);

            $content = htmlspecialchars_decode($content);

            //print_r($content);

//            $content = str_replace('"/Uploads/','"http://mall.k30000.com/Uploads/',$content);
        }



        $course_detail['content'] = html_entity_decode($content);
        $course_detail['speaker'] = json_decode($course_detail['speaker'], 1);
        //$course_detail['content'] = html_entity_decode($course_detail['content']);
        return $course_detail;
    }


    /**
     * @param $sid
     * @param $uid
     * @param $p
     * @return false|\PDOStatement|string|\think\Collection
     * 获取某学员试听课程列表
     */
    public function getStudentListeningCourseList($sid, $uid, $p){
        //获取自身的课程
        $condition = array();
        $condition['cs.uid'] = $uid;
        $condition['cs.formal_status'] = 1;
        $condition['cs.ourclass_status'] = 1;
        $condition['c.course_status'] = 1;

        $field = 'cs.courseid,cs.uid';

        $my_course_list = db()->name('course_students')
                        ->alias('cs')
                        ->field($field)
                        ->join('course c', 'c.courseid = cs.courseid')
                        ->where($condition)
                        ->select();

        //保存自身课程ids
        $my_course_ids = [];
        if($my_course_list){
            foreach ($my_course_list as $key => $val){
                $my_course_ids[$key] = $val['courseid'];
            }
        }

        $cur_time = time(); //当前时间
        $where = [
            'sid' => $sid,
            'status' => 1, //可试听状态为1
            'schoolovertime' => ['>',$cur_time], //当前时间小于课程结束时间
            'deadline' => ['>',$cur_time], //当前时间小于试听申请结束时间
            'course_status' => 1
        ];
        if($my_course_ids){
            $where['courseid'] = ['not in', $my_course_ids];
        }

        $f = 'courseid,sid,name,speaker,schooltime,schoolovertime,description,content,pic,addtime,status,deadline';

        $course_list = db('course')->field($f)->where($where)->limit(($p-1) * $this->pageSize , $this->pageSize)->select();

        if($course_list){
            foreach ($course_list as $k => $v){
                $course_list[$k]['schooltime'] = date('Y-m-d H:i:s',$v['schooltime']);
                $course_list[$k]['schoolovertime'] = date('Y-m-d H:i:s',$v['schoolovertime']);
                $course_list[$k]['deadline'] = date('Y-m-d H:i:s',$v['deadline']);
                $course_list[$k]['content'] = json_decode(htmlspecialchars_decode($v['content']), 1);
                $course_list[$k]['speaker'] = json_decode($v['speaker'], 1);

                $con = [
                    'uid' => $uid,
                    'courseid' => $v['courseid'],
                    'status' => ['<>', 2]
                ];
                $join = db('course_listening')->where($con)->order('courseid DESC')->find();
                if($join){
                    if($join['status'] == 0){
                        //待审核
                        $course_list[$k]['listening_status'] = 1;
                    } elseif ($join['status'] == 1){
                        //已通过
                        $course_list[$k]['listening_status'] = 2;
                    }
                } else {
                    //可申请
                    $course_list[$k]['listening_status'] = 0;
                }
            }
        }
        return $course_list;
    }

    /**
     * @param $sid
     * @param $uid
     * @param $mobile
     * @param $sms_code
     * @return array
     * @throws \think\Exception
     * 绑定手机号码
     */
    public function bind_phone($sid, $uid, $mobile, $sms_code){
        //校验验证码
        if(Sms::check_sms_code($mobile, $sms_code) === false){
            return ['status' => 0, 'msg' => '验证码错误'];
        }

        //查找该手机号是否已经绑定微信
        $phone_info = db('students')->where(['phone' => $mobile, 'sid' => $sid, 'status' => 1])->find();
        if($phone_info['uid'] > 0 && $phone_info['phone_bind_status'] == 1){
            return ['status' => 0, 'msg' => '该手机号已绑定,请重新输入!'];
        }

        //查询是否在绑定手机号码之前更新过用户其他信息

        //若更新过，则在students表中存在一条数据A，且拥有uid，
        //此时，仅需将A数据更新过的字段（姓名、生日、身份证、单位、主营业务、人生格言、兴趣爱好）同步到phone那条数据B，
        //更新数据B中的uid和phone_bind_status，并删除数据A

        //若未更新过，则直接更新uid，并将手机号码绑定状态置为1；

        $student_info = db('students')->where(['uid' => $uid, 'sid' => $sid, 'status' => 1])->find();
        if(empty($student_info)){

            if(empty($phone_info)){
                //默认主页
                $init_id = db('user_students_theme')->where(['sid' => $sid])->order('default_status desc')->value('init_id');
                //uid查询为空且phone查询为空，说明无数据
                $data = [
                    'uid' => $uid,
                    'sid' => $sid,
                    'phone' => $mobile,
                    'phone_bind_status' => 1,
                    'status' => 1,
                    'addtime' => time(),
                    'classid' => 0,
                    'formal_status' => 0,
                    'homepage_style' => $init_id
                ];
                $res = db('students')->insertGetId($data);
                //更新user_integral表中的students_id
                db('user_integral')->where(['userid' => $uid,'sid' => $sid])->update(['students_id' => $res]);

            } else {
                //uid查询为空且phone不为空
                $update_data = [
                    'uid' => $uid,
                    'phone_bind_status' => 1
                ];
                // 这里更新了学员表的UID，同步也要更新班级学员表的
                $res = db('students')->where(['id' => $phone_info['id']])->update($update_data);
                // 同步更新班级学员表里面的记录，防止下一步误判xiu
                $res2 = db('class_students')->where(['studentsid' => $phone_info['id']])->update(['uid' => $uid]);

                //更新user_integral表中的students_id,pid,counselor_id
                $counselor_id = $phone_info['counselor_id'];
                db('user_integral')->where(['userid' => $uid,'sid' => $sid])->update(['students_id' => $phone_info['id'],'counselor_id' => $counselor_id,'parent_id'=>$counselor_id]);
                //推送消息
                $tplServer = new WxTplMsgService();
                $tplServer->send($sid,$uid,'user');
                //班级签单学员+1
                if($phone_info['classid'] > 0){
                    $class_info = db('classes')->where('classid',$phone_info['classid'])->find();
                    if($class_info){
                        //studentsid = 0 的情况
                        $class_students = db('class_students')
                                        ->where(['sid' => $sid, 'uid' => $uid, 'classid' => $phone_info['classid'], 'studentsid' => 0])
                                        ->find();
                        if($class_students){
                            db('class_students')
                                ->where(['sid' => $sid, 'uid' => $uid, 'classid' => $phone_info['classid'], 'studentsid' => 0])
                                ->setField('studentsid', $phone_info['id']);
                        } else {
                            //uid = 0 的情况
                            $class_students2 = db('class_students')
                                ->where(['sid' => $sid, 'studentsid' => $phone_info['classid'], 'classid' => $phone_info['classid'], 'uid' => 0])
                                ->find();
                            if($class_students2){
                                db('class_students')
                                    ->where(['sid' => $sid, 'studentsid' => $phone_info['classid'], 'classid' => $phone_info['classid'], 'uid' => 0])
                                    ->setField('uid', $uid);
                            } else {
                                //班级学员关联表
                                $insert_data = [
                                    'uid' => $uid,
                                    'classid'=> $phone_info['classid'],
                                    'sid' => $sid,
                                    'addtime' => time(),
                                    'studentsid' => $phone_info['id']
                                ];
                                $cs_info = db('class_students')
                                            ->where(['uid' => $uid, 'classid' => $phone_info['classid'], 'studentsid' => $phone_info['id'], 'sid' => $sid])
                                            ->find();
                                if(!$cs_info){
                                    db('class_students')->insert($insert_data);
                                }
                            }
                        }

                       /* //班级学员关联表
                        $insert_data = [
                            'uid' => $uid,
                            'classid'=> $phone_info['classid'],
                            'sid' => $sid,
                            'addtime' => time(),
                            'studentsid' => $phone_info['id']
                        ];
                        db('class_students')->insert($insert_data);*/
                        //更新班级表
                        db('classes')->where('classid',$phone_info['classid'])->setInc('total_numbe');
                    }
                }
            }

            /*$classid = $student_info['classid'];
            $students_id = $student_info['id'];*/
            //$uid

            // 1。class_students，更新这个学员的uid
            // 2。如果班级ID不为0，查询出班级学员表里面，是否有数据，如果没有就写入

        } else {

            if( empty($phone_info) ){
                //uid查询不为空且phone查询为空
                $update_data = [
                    'phone' => $mobile,
                    'phone_bind_status' => 1
                ];
                $res = db('students')->where(['id' => $student_info['id']])->update($update_data);
            } else {
                //uid查询不为空且phone不为空
                $update_data = [
                    'phone_bind_status' => 1,
                    'uid' => $uid
                ];
                if(isset($student_info['name'])){
                    $update_data['name'] = $student_info['name'];
                }
                if(isset($student_info['birthday'])){
                    $update_data['birthday'] = $student_info['birthday'];
                }
                if(isset($student_info['cardid'])){
                    $update_data['cardid'] = $student_info['cardid'];
                }
                if(isset($student_info['company'])){
                    $update_data['company'] = $student_info['company'];
                }
                if(isset($student_info['business'])){
                    $update_data['business'] = $student_info['business'];
                }
                if(isset($student_info['life_motto'])){
                    $update_data['life_motto'] = $student_info['life_motto'];
                }
                if(isset($student_info['hobby'])){
                    $update_data['hobby'] = $student_info['hobby'];
                }

                $res = db('students')->where(['id' => $phone_info['id']])->update($update_data);
                //db('students')->where(['id'=>$student_info['id']])->delete();
            }

        }
        if($res === false){
            return ['status' => 0, 'msg' => '绑定失败'];
        } else {
            $student_info_temp = db('students')->where(['uid' => $uid, 'sid' => $sid])->find();
            $studentsid = $student_info_temp['id'];
            //根据students表中的classid插入class_students表，course_students表
            $this->add_course_student($sid, $uid,$studentsid);
            //是否有学员姓名，公司
            $info = db('students')->where(['phone' => $mobile, 'sid' => $sid, 'status' => 1])->find();
            if(empty($info['name'])||empty($info['company'])){
                return ['status' => 2, 'msg' => '绑定成功'];
            }else{
                return ['status' => 1, 'msg' => '绑定成功'];
            }

        }
    }

    /**
     * 根据students表中的classid添加班级学员、课程学员关联数据
     * @param array $condition
     * @return mixed|number
     */
    public function add_course_student($sid, $uid,$studentsid=0){
        $info = db('students')->where(['uid' => $uid, 'status' => 1])->find();
        if($info['classid'] > 0){
            //课程信息
            $class_info = db('classes')->where(['classid' => $info['classid'],'sid' => $sid])->find();
            if($class_info){
                // 判断一下，如果班级学员表里面没有，才写入进去
                $class_students_temp = db('class_students')->where(['uid' =>$uid,'sid'=>$sid, 'classid' => $info['classid']])->find();
                if(!$class_students_temp) {
                    //班级学员关联表
                    $class_students_data = [
                        'uid' => $uid,
                        'sid' => $sid,
                        'studentsid' => $studentsid,
                        'classid' => $info['classid'],
                        'addtime' => time()
                    ];

                    $cs_info = db('class_students')
                        ->where(['uid' => $uid, 'classid' => $info['classid'], 'studentsid' => $studentsid, 'sid' => $sid])
                        ->find();
                    if(!$cs_info){
                        db('class_students')->insert($class_students_data);
                    }
                }

                //学员课程关联表
                $course_list = db('course_class')->where(['classid' => $info['classid']])->field('courseid')->select();

                if(!empty($course_list)){
                    foreach($course_list as $k => $v){
                        $course_students_data[$k] = [
                            'uid' => $uid,
                            'sid' => $sid,
                            'attend_status' => 0,
                            'sign_status' => 0,
                            'apply_status' => 0,
                            'formal_status' => 1,
                            'ourclass_status' => 1,
                            'addtime' => time(),
                            'courseid' => $v['courseid'],
                            'studentsid' => $studentsid,
                        ];

                    }
                    db('course_students')->insertAll($course_students_data);
                }
            }
        }
        return true;
    }


    public function applyListeningCourse(Request $request, $sid, $uid){
        //课程Id
        $course_id = $request->param('course_id');

        //保存课程试听数据
        $course_listen_data = array();

        //判断当前是 先完善资料后申请试听 还是 直接申请试听
        $type = $request->has('type') ? $request->param('type') : '';

        // 启动事务
        Db::startTrans();

        //完善资料
        if($type == 'complete'){
            $phone = $request->param('phone');
            $post_sms_code = $request->param('sms_code');
            $name = $request->param('name');
            $company = $request->param('company');
            $position = $request->param('position');

            if( empty($phone) || empty($post_sms_code) || empty($name) || empty($company) || empty($position)) {
                return ['status' => 0, 'msg' => '输入信息不完善'];
            }

            //校验手机号码
            if(!Util::is_mobile($phone)){
                return ['status' => 0, 'msg' => '手机号码格式不正确'];
            }

            //验证验证码
            if(!Sms::check_sms_code($phone,$post_sms_code)){
                return ['status' => 0, 'msg' => '验证码错误'];
            }

            //查找该手机号是否已经绑定微信
            $phone_info = db('students')->where(['phone' => $phone, 'sid' => $sid, 'status' => 1])->find();
            if($phone_info['uid'] > 0 && $phone_info['phone_bind_status'] == 1){
                return ['status' => 0, 'msg' => '该手机号已绑定,请重新输入!'];
            }

            //查询是否在绑定手机号码之前更新过用户其他信息

            //若更新过，则在students表中存在一条数据A，且拥有uid，
            //此时，仅需将A数据更新过的字段（姓名、生日、身份证、单位、主营业务、人生格言、兴趣爱好）同步到phone那条数据B，
            //更新数据B中的uid和phone_bind_status，并删除数据A

            //若未更新过，则直接更新uid，并将手机号码绑定状态置为1；
            $student_info = db('students')->where(['uid' => $uid, 'sid' => $sid, 'status' => 1])->find();
            $company_info[0] = ['cname' => $company,'position' => $position,'address' => ''];
//            $company_info = serialize($company_info);
            $company_info = Util::serializeStr($company_info);
            if(empty($student_info)){
                if(empty($phone_info)){
                    //默认主页
                    $init_id = db('user_students_theme')->where(['sid' => $sid])->order('default_status desc')->value('init_id');
                    //uid查询为空且phone查询为空，说明无数据
                    $data = [
                        'uid' => $uid,
                        'sid' => $sid,
                        'phone' => $phone,
                        'phone_bind_status' => 1,
                        'status' => 1,
                        'addtime' => time(),
                        'classid' => 0,
                        'formal_status' => 0,
                        'name' => $name,
                        'company' => $company_info,
                        'homepage_style' => $init_id
                    ];

                    $save_res = db('students')->insertGetId($data);
                    //更新user_integral表中的students_id
                    db('user_integral')->where(['userid' => $uid,'sid' => $sid])->update(['students_id' => $save_res]);
                } else {
                    //uid查询为空且phone不为空
                    $update_data = [
                        'uid' => $uid,
                        'phone_bind_status' => 1
                    ];
                    $save_res = db('students')->where(['id' => $phone_info['id']])->update($update_data);
                    //更新user_integral表中的students_id
                    db('user_integral')->where(['userid' => $uid,'sid' => $sid])->update(['students_id' => $phone_info['id']]);
                }
            } else {
                if(empty($phone_info)){
                    //uid查询不为空且phone查询为空
                    $update_data = [
                        'phone' => $phone,
                        'phone_bind_status' => 1,
                        'name' => $name,
                        'company' => $company_info
                    ];

                    $save_res = db('students')->where(['id' => $student_info['id']])->update($update_data);
                }else{
                    //uid查询不为空且phone不为空
                    $update_data = [
                        'phone_bind_status' => 1,
                        'uid' => $uid
                    ];

                    if(isset($student_info['name'])){
                        $update_data['name'] = $student_info['name'];
                    }
                    if(isset($student_info['birthday'])){
                        $update_data['birthday'] = $student_info['birthday'];
                    }
                    if(isset($student_info['cardid'])){
                        $update_data['cardid'] = $student_info['cardid'];
                    }
                    if(isset($student_info['company'])){
                        $update_data['company'] = $student_info['company'];
                    }
                    if(isset($student_info['business'])){
                        $update_data['business'] = $student_info['business'];
                    }
                    if(isset($student_info['life_motto'])){
                        $update_data['life_motto'] = $student_info['life_motto'];
                    }
                    if(isset($student_info['hobby'])){
                        $update_data['hobby'] = $student_info['hobby'];
                    }

                    $save_res = db('students')->where(['id' => $phone_info['id']])->update($update_data);
                    //db('students')->where(['id' => $student_info['id']])->delete();
                }
            }

            //if($save_res === false){
                // 回滚事务
                //Db::rollback();
                //return ['status' => 0, 'msg' => '用户信息保存失败'];
            //}
            $student_info_temp = db('students')->where(['uid' => $uid, 'sid' => $sid])->find();
            $studentsid = $student_info_temp['id'];
            //根据students表中的classid插入class_students表，course_students表
            $this->add_course_student($sid, $uid,$studentsid);
        }

        //已完善资料后申请试听
        $course = db('course')->where(['courseid' => $course_id,'status' => 1])->find();
        if(empty($course)){
            return ['status' => 0,'msg' => '该课程暂时无法申请试听'];
        }

        $course_listen = db('course_listening')->where(['uid' => $uid,'courseid' => $course_id])->find();

        //判断是否已经申请过试听
        if(empty($course_listen)){
            //判断改学员是否完善资料
            $student_info = db('students')->where(['uid' => $uid,'sid' => $sid,'status' => 1])->find();

            //学员信息为空，则插入学员信息
            if(empty($student_info)){
                return ['status' => 2, 'msg' => '请完善个人信息'];
            } else {
                //资料不完善
//                if(empty($student_info['phone']) || ($student_info['phone_bind_status']!=1) || empty($student_info['name']) || empty($student_info['company']) ){
                if(empty($student_info['phone']) || empty($student_info['name']) || empty($student_info['company']) ){
                    return ['status' => 2, 'msg' => '请完善个人信息'];
                }
            }
            //插入course_listening数据和course_students数据
            $course_listen_data = [
                'uid' => $uid,
                'sid' => $sid,
                'courseid' => $course_id,
                'apply_time' => time(),
                'status' => 0
            ];
            $course_listen_res = db('course_listening')->insert($course_listen_data);

            if($course_listen_res === false){
                Db::rollback();
                return ['status' => 0,'msg' => '申请失败'];
            }

            //写入客户轨迹
            $trackService = new TrackService();
            $track = '学员：'.$student_info['name'].'，申请了《'.$course['name'].'》课程试听';
            $counselor_id = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_id');
            $trackService->writeTrack($track, $counselor_id);

            //提交事务
            Db::commit();
            return ['status' => 1,'msg' => '申请成功'];

        } else {
            return ['status' => 0,'msg' => '您已申请过此课程了'];
        }
    }


    /**
     * @param $sid
     * @param $uid
     * @param $course_id
     * @param $attend_status
     * 是否确认出席此课程
     */
    public function attendCourse($sid, $uid, $course_id, $attend_status,$referer=''){

        $this->updateaTaskLog($attend_status,$referer);

        $where = [
            'uid' => $uid,
            'courseid' => $course_id
        ];

        $course_student_info = db('course_students')->where($where)->find();
        if(empty($course_student_info)){
//            return ['status' => 0,'msg' => '暂时无法操作'];
            //查询是否为本班学员
            $classes = db('class_students')->field('classid')->where(['sid' => $sid, 'uid' => $uid])->select();
            $class_ids = [];
            if($classes){
                foreach($classes as $k => $v){
                    $class_ids[$k] = $v['classid'];
                }
                $course_class = db('course_class')->where(['courseid' => $course_id, 'classid' => ['in', $class_ids]])->find();
                if($course_class){
                    $data = [
                        'courseid' => $course_id,
                        'uid' => $uid,
                        'sid' => $sid,
                        'attend_status' => $attend_status,
                        'formal_status' => 1,
                        'ourclass_status' => 1,
                        'addtime' => time()
                    ];
                    $r = db('course_students')->insert($data);
                    return $r === false ? ['status' => 0,'msg' => '操作失败'] : ['status' => 1,'msg' => '操作成功'];
                } else {
                    return ['status' => 0,'msg' => '暂时无法操作'];
                }
            } else {
                return ['status' => 0,'msg' => '暂时无法操作'];
            }

        }

        if($course_student_info['attend_status'] == 0){
            //未确认
            //更新状态
            $res = db('course_students')->where($where)->setField('attend_status',$attend_status);
            if($res === false){
                return ['status' => 0,'msg' => '操作失败'];
            } else {
                return ['status' => 1,'msg' => '操作成功'];
            }
        } else {
            //已确认
            return ['status' => 2,'msg' => '已确认过'];
        }

    }

    /**
     * 先放在这里
     */
    public function updateaTaskLog($attend_status,$referer)
    {

        if($referer) {
            $_back_url = urldecode($referer);
            $urlArray = parse_url($_back_url);
            $queryArr = explode('&', $urlArray['query']);
            foreach($queryArr as $para)
            {
                if (preg_match("/^task_log_id=\d+$/", $para)) {
                    $task_log_id_array = explode('=', $para);
                    $task_log_id = $task_log_id_array[1];

                    //1-确认来，2-确认不来，3-不确定来不来
                    if($task_log_id) {

                        db('course_push_task_log')
                            ->where(array('id' => $task_log_id))
                            ->update(array('operate_status' => $attend_status, 'operate_time' => time()));

                        $task_log = db('course_push_task_log')
                            ->where(array('id'=>$task_log_id))->find();


                        db('course_push_task_detail')
                            ->where(array('course_push_task_id'=>$task_log['course_push_task_id'],'studentsid'=>$task_log['studentsid']))
                            ->update(array('operate_status'=>$attend_status));
                    }
                }
            }

        }
    }

    /**
     * 新增或编辑课程
     * @param $sid
     * @param $postParam
     * @return array
     * @throws \think\Exception
     */
    public function saveCourse($sid, $postParam){
        $start_time = strtotime($postParam['schooltime']);
        $over_time = strtotime($postParam['schoolovertime']);
        if($start_time < time() || $over_time < time()){
            return ['status' => 0,'msg' => '请选择正确的课程时间'];
        }
        if($start_time >= $over_time){
            return ['status' => 0,'msg' => '课程开始时间不能大于结束时间'];
        }

        $id = $postParam['id'] ?? 0;
        $class_ids = $postParam['class_id'] ?? [];

        //更新课程详情时，若发起试听，则与课程结束时间比较
        if($id > 0){
            $course_info = db('course')->where(['courseid' => $postParam['id']])->find();
            if($course_info && $course_info['status'] == 1){
                if($over_time < $course_info['deadline']){
                    return ['status' => 0,'msg' => '发起试听时间不能大于课程结束时间'];
                }
            }
        }

        $data = [];
        $data['name'] = $postParam['name'];
        $data['speaker'] = json_encode($postParam['speaker'], JSON_UNESCAPED_UNICODE);
        $data['schooltime'] = $start_time;
        $data['schoolovertime'] = $over_time;
        $data['pic'] = $postParam['pic'];
        $data['description'] = $postParam['description'] ?? '';
        $data['content'] = $postParam['content'] ?? '';
        $data['poster_imgs'] = $postParam['poster_imgs'] ? json_encode($postParam['poster_imgs']) : '';
        $data['using_class_setting_push'] = $postParam['using_class_setting_push'] ? 1 : 0;
        $data['course_push_tpl_id'] = $postParam['course_push_tpl_id'] ?? 0;
        $data['course_status'] = 0;

        if($this->isTemplateStore($sid)){
            //模版店铺记录学院Id
            $data['academy_id'] = $postParam['academy_id'] ?? 0;
            //模版店铺必须绑定班级
            if(!isset($postParam['class_id'])){
                return ['status' => 0,'msg' => '请绑定班级'];
            }
        }

        if($id > 0){
            $add_flag = false;
            $data['edittime'] = time(); //更新时间
            //更新
            $res = db('course')->where(['courseid' => $id, 'sid' => $sid])->update($data);
            if($res === false) {
                return ['status' => 0, 'msg' => '编辑失败'];
            }
            //若没有课程二维码，则添加
            $course_info = db('course')->where(['courseid' => $id, 'sid' => $sid])->find();

            if(!$this->isTemplateStore($sid)){
                if(empty($course_info['ticket']) || empty($course_info['ticket_url']) || empty($course_info['qrcode_url'])){
                    // 生成课程的签到二维码  模版店铺发布绕过
                    $this->getCourseQrcodeUrl($sid, $id);
                }

            }
        } else {
            //新增
            $add_flag = true;
            $data['sid'] = $sid;
            $data['addtime'] = time();
            $data['face_sign_code'] = Util::getRandomStr(10);  //生成7位随机字符串，用于人脸签到登录码
            $id = db('course')->insertGetId($data);
            if(!$id){
                return ['status' => 0, 'msg' => '新增失败'];
            }

            if(!$this->isTemplateStore($sid)){
                // 生成课程的签到二维码  模版店铺发布绕过
                $this->getCourseQrcodeUrl($sid, $id);
            }
        }

        //添加关联班级时
        if(is_array($class_ids) && count($class_ids) > 0){
            //添加课程推送模版任务
            if(!$this->isTemplateStore($sid)){
                $coursePushService = new CoursePushTplService();
                $coursePushService->addCoursePushTask($sid, $id, $class_ids, $data['course_push_tpl_id'], $add_flag, $data['using_class_setting_push']);
            }

            $courseClassService = new CourseClassService();
            $r = $courseClassService->addCourseClass($id, $class_ids);
//                $res = $this->addFormalCourseStudents($sid, $id, $class_ids);
//                if($r === false || $res === false){
            if($r === false){
                return ['status' => 0, 'msg' => '保存失败'];
            }
        } else {
            if($id){
                // 取消关联班级
                db('course_class')->where(['courseid' => $id])->delete();
            }
        }

        return ['status' => 1, 'msg' => '保存成功'];
    }

    public function addFormalCourseStudents($sid, $course_id, $class_ids){
        //先删除未签到的正式学员
        db('course_students')
            ->where([
                'sid' => $sid,
                'courseid' => $course_id,
                'sign_status' => 0,
                'formal_status' => 1,
                'ourclass_status' => 1,
                'apply_status' => 0
            ])
            ->delete();
        $users = db('class_students')->field('uid,studentsid')->where(['sid' => $sid, 'classid' => ['in', $class_ids]])->select();
        $uids = [];
        if($users){
            foreach ($users as $key => $val) {
                $uids[$key] = $val['uid'];
            }
            $uids = array_unique($uids);
        } else {
            return true;
        }

        $data = [];
        foreach($uids as $k => $v){
            $data[$k]['courseid'] = $course_id;
            $data[$k]['uid'] = $v;
            $data[$k]['sid'] = $sid;
            $data[$k]['attend_status'] = 0;
            $data[$k]['sign_status'] = 0;
            $data[$k]['addtime'] = time();
            $data[$k]['formal_status'] = 1;
            $data[$k]['ourclass_status'] = 1;
            $data[$k]['apply_status'] = 0;
            $data[$k]['studentsid'] = $v['studentsid'];
        }

        return db('course_students')->insertAll($data);
    }

    /**
     * 获取课程签到二维码
     * @param $sid
     * @param $course_id
     * @return array
     * @throws \think\Exception
     */
    public function getCourseQrcodeUrl($sid, $course_id){
        $course = db('course')->field('ticket,ticket_url')->where(['sid' => $sid, 'courseid' => $course_id])->find();
        if (!$course) {
            return ['status' => 0, 'msg' => '课程不存在'];
        }
        if (!empty($course['ticket']) && !empty($course['ticket_url'])) {
            return ['status' => 1, 'url' => $course['ticket_url']];
        } else {
            $wxService = new WeixinService();
            $qrurl = $wxService->get_forever_qrcode($sid, 'qrscene_course_'.$course_id);
            $qrurl = json_decode($qrurl,1);

            db('course')
                ->where(['sid' => $sid, 'courseid' => $course_id])
                ->update(['ticket' => $qrurl['ticket'], 'ticket_url' => $qrurl['url'],'qrcode_url'=>$qrurl['qrcode_url']]);

            return ['status' => 1, 'url' => $qrurl['qrcode_url']];
        }
    }

    /**
     * 保存课程内容
     * @param $sid
     * @param $id
     * @param $content
     * @return int
     */
    public function saveCourseContent($sid, $id, $content){
        return db('course')->where(['courseid' => $id, 'sid' => $sid])->setField('content', $content);
    }

    /**
     * 获取课程列表
     * @param $sid
     * @param $type
     * @param $search
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getCourseList($sid, $type, $search, $p, $pageSize){
        $data = [];

        $cur_time = time();
        $where = [];
        if(!empty($search)){
            $where['name|speaker'] = ['like', '%'.$search.'%'];
        }
        $where['sid'] = $sid;
//        $where['course_status'] = 1;
        $where['course_status'] = ['in', [0,1]];

        switch($type){
            case 'all':
                break;
            case 'unstart':
                $where['schooltime'] = ['>',$cur_time];
                break;
            case 'underway':
                $where['schooltime'] = ['<=',$cur_time];
                $where['schoolovertime'] = ['>=',$cur_time];
                break;
            case 'canlisten':
                $where['status'] = 1;
                break;
            case 'finished':
                $where['schoolovertime'] = ['<=',$cur_time];
                break;
            default:
                break;
        }

        //获取总数
        $data['page']['count'] = db('course')->where($where)->count();

        $field = 'courseid,name,speaker,schooltime,schoolovertime,pic,deadline,qrcode_url,release_status,start_intelligent_push,
        course_price,stock,apply_deadline,is_allow_buy,is_allow_coupon,payment_type,course_status,need_avatar,face_sign_code';
        $list = db('course')->field($field)->where($where)->order('courseid DESC')->limit(($p - 1)*$pageSize, $pageSize)->select();

        //所有课程数量
        $all_course_count = $this->getAllCourseCount($sid);
        //未开始的课程数量
        $unstart_course_count = $this->getUnstartCourseCount($sid);
        //正在进行中的课程数量
        $start_course_count = $this->getStartCourseCount($sid);
        //可试听的课程数量
        $canlisten_course_count = $this->getCanListenCourseCount($sid);
        //已结束的课程数量
        $finished_course_count = $this->getFinishedCourseCount($sid);

        foreach($list as $k => $v){
            if($cur_time < $v['schooltime']){
                $list[$k]['course_progress_name'] = '未开始';
                $list[$k]['course_progress'] = 0;
            } elseif ($cur_time >= $v['schoolovertime']){
                $list[$k]['course_progress_name'] = '已结束';
                $list[$k]['course_progress'] = 2;
            } elseif ( ($cur_time >= $v['schooltime']) && ($cur_time <= $v['schoolovertime'])){
                $list[$k]['course_progress_name'] = '正在进行';
                $list[$k]['course_progress'] = 1;
            }

            $list[$k]['schooltime'] = date('Y-m-d H:i:s', $v['schooltime']);
            $list[$k]['schoolovertime'] = date('Y-m-d H:i:s', $v['schoolovertime']);
            $list[$k]['apply_deadline'] = $v['apply_deadline'] ? date('Y-m-d H:i:s', $v['apply_deadline']) : 0;
            $list[$k]['deadline'] = $v['deadline'] ? date('Y-m-d H:i:s', $v['deadline']) : '--';
            $list[$k]['speaker'] = json_decode($v['speaker'], 1);
            $list[$k]['payment_type'] = $v['payment_type'] ? explode(',', $v['payment_type']) : '';

            //获取课程关联的班级信息
            $join_class = $this->getCourseClass($sid, $v['courseid'], 'cl.classid,cl.name');
            $join_class_ids = [];  //保存参与班级Id
            if($join_class){
                $join_class_name = array();
                foreach ($join_class as $key => $val){
                    $join_class_ids[$key] = $val['classid'];
                    $join_class_name[$key] = $val['name'];
                }
                $join_class_name_str = implode('、', $join_class_name);
            } else {
                $join_class_name_str = '暂无';
            }
            $list[$k]['join_class'] = $join_class_name_str;

            //获取正式学员列表及确认参与人数
            /*$formal_students = $this->getFormalCourseStudentsList($v['courseid']);
            $formal_students_confirm_join = 0;
            if($formal_students){
                foreach ($formal_students as $k2 => $v2){
                    if($v2['attend_status'] == 1){
                        $formal_students_confirm_join++;
                    }
                }
            }
//            $list[$k]['formal_students_count'] = count($formal_students) > 0 ? count($formal_students) : 0;
            $list[$k]['formal_students_count'] = $this->getFormalStudentsCountByCourseid($v['courseid']);
            $list[$k]['formal_students_join_count'] = $formal_students_confirm_join > 0 ? $formal_students_confirm_join : 0;*/
            $list[$k]['formal_students_count'] = $this->getFormalStudentsCountByCourseid($v['courseid']);
            $list[$k]['formal_students_join_count'] = $this->getFormalCourseStudentsAttendCount($v['courseid']);


            //获取试听人数列表及确认参与人数
            /*$listening_students = $this->getListeningCourseStudentsList($v['courseid']);
            $listening_students_confirm_join = 0;
            if($listening_students){
                foreach ($listening_students as $k3 => $v3){
                    if($v3['attend_status'] == 1){
                        $listening_students_confirm_join++;
                    }
                }
            }
            $list[$k]['listening_students_count'] = count($listening_students) > 0 ? count($listening_students) : 0;
            $list[$k]['listening_students_confirm_join'] = $listening_students_confirm_join > 0 ? $listening_students_confirm_join : 0;


            //获取试听结束时间
            $deadline = db('course')->where(['courseid' => $v['courseid']])->value('deadline');
            $list[$k]['listening_students_deadline'] = $deadline ? date('Y-m-d H:i:s', $deadline) : '';*/

            //学员总人数
            $list[$k]['students_count'] = $this->getStudentsCount($v['courseid']);

            //替换旧系统中的课程二维码和课程主图
            $list[$k]['qrcode_url'] = $this->replaceOldCourseInfo($v['qrcode_url']);
//            $list[$k]['pic'] = $this->replaceOldCourseInfo($v['pic']);
        }

        $data['page']['all_course_count'] = $all_course_count;
        $data['page']['unstart_course_count'] = $unstart_course_count;
        $data['page']['start_course_count'] = $start_course_count;
        $data['page']['canlisten_course_count'] = $canlisten_course_count;
        $data['page']['finished_course_count'] = $finished_course_count;

        $data['content'] = $list;

        return $data;
    }

    //替换旧系统中的课程二维码
    private function replaceOldCourseInfo($qrcode_url){
        if(substr( $qrcode_url, 0, 1 ) == '/'){
            $qrcode_url = 'http://mall.k30000.com'.$qrcode_url;
        }
//        if(strpos($qrcode_url, '/Uploads')){
//            $qrcode_url = 'http://mall.k30000.com'.$qrcode_url;
//        }
        return $qrcode_url;
    }

    /**
     * 获取所有课程数量
     * @param $sid
     * @return int|string
     */
    public function getAllCourseCount($sid){
        return db('course')->where(['sid' => $sid])->count();
    }

    /**
     * 获取未开始课程数量
     * @param $sid
     * @return int|string
     */
    public function getUnstartCourseCount($sid){
        return db('course')->where(['sid' => $sid, 'schooltime' => ['>', time()]])->count();
    }

    /**
     * 获取已开始课程数量
     * @param $sid
     * @return int|string
     */
    public function getStartCourseCount($sid){
        return db('course')->where(['sid' => $sid, 'schooltime' => ['<=', time()], 'schoolovertime' => ['>=', time()]])->count();
    }

    /**
     * 获取可试听课程数量
     * @param $sid
     * @return int|string
     */
    public function getCanListenCourseCount($sid){
        return db('course')->where(['sid' => $sid, 'status' => 1])->count();
    }

    /**
     * 获取已结束课程数量
     * @param $sid
     * @return int|string
     */
    public function getFinishedCourseCount($sid){
        return db('course')->where(['sid' => $sid, 'schoolovertime' => ['<=', time()]])->count();
    }

    /**
     * 获取课程学生数量
     * @param $course_id
     * @return int|string
     */
    public function getStudentsCount($course_id){
        return db('course_students')->where(['courseid' => $course_id])->count();
    }

    /**
     * 获取课程关联班级信息
     * @param $sid
     * @param $course_id
     * @param string $field
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCourseClass($sid, $course_id, $field = '*'){
        $condition = [
            'cr.sid' => $sid,
            'cr.courseid' => $course_id,
            'cl.status' => 1
        ];
        return db()->name('course cr')
                ->field($field)
                ->join('course_class cc', 'cc.courseid = cr.courseid')
                ->join('classes cl','cc.classid = cl.classid')
                ->where($condition)
                ->select();
    }

    /**
     * 获取某课程正式学员列表
     * @param $course_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getFormalCourseStudentsList($course_id){
        $where = [
            'courseid' => $course_id,
            'formal_status' => 1,
            'ourclass_status' => 1
        ];
        return db('course_students')->where($where)->select();
    }

    /**
     * 获取某课程正式学员确认参与数量
     * @param $course_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getFormalCourseStudentsAttendCount($course_id){
        $where = [
            'courseid' => $course_id,
            'formal_status' => 1,
            'ourclass_status' => 1,
            'attend_status' => 1
        ];
        return db('course_students')->where($where)->count();
    }

    /**
     * 获取某课程试听学员列表
     * @param $course_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getListeningCourseStudentsList($course_id){
        $where = [
            'courseid' => $course_id,
            'apply_status' => ['in', [1,2]]
        ];
        return db('course_students')->where($where)->select();
    }


    /**
     * 后台获取课程详情
     * @param $sid
     * @param $course_id
     * @param $type
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getCourseDetailAdmin($sid, $course_id, $type){
        $data = []; //保存数据

        //获取课程基本信息
//        $course_info = $this->getCourseDetail($course_id);
        $course_info = db('course')->where(['sid' => $sid, 'courseid' => $course_id])->find();

        if(empty($course_info)){
            return false;
        }

        $cur_time = time();
        if($course_info['schooltime'] > $cur_time){
            $course_info['progress_status'] = 0; //未开始
        } elseif ($course_info['schoolovertime'] < $cur_time) {
            $course_info['progress_status'] = 2; //未结束
        } elseif ( ($course_info['schooltime'] <= $cur_time) && ($course_info['schoolovertime'] >= $cur_time) ){
            $course_info['progress_status'] = 1; //正在进行中
        }

        $course_info['schooltime'] = date('Y-m-d H:i:s', $course_info['schooltime']);
        $course_info['schoolovertime'] = date('Y-m-d H:i:s', $course_info['schoolovertime']);
        $course_info['deadline'] = date('Y-m-d H:i:s', $course_info['deadline']);
        $course_info['content'] = html_entity_decode($course_info['content']);

        $course_info['qrcode_url'] = $this->replaceOldCourseInfo($course_info['qrcode_url']);
//        $course_info['pic'] = $this->replaceOldCourseInfo($course_info['pic']);
        $course_info['poster_imgs'] = $course_info['poster_imgs'] ? json_decode($course_info['poster_imgs'], 1) : '';
        $course_info['speaker'] = json_decode($course_info['speaker'], 1);

        $data['course_info'] = $course_info;

        //获取课程关联的班级信息
        $join_class = $this->getCourseClass($sid, $course_id, 'cl.classid,cl.name');
        if($join_class){
            $join_class_name = array();
            foreach ($join_class as $k => $v){
                $join_class_name[$k] = $v['name'];
            }
            $join_class_name_str = implode('、', $join_class_name);
        } else {
            $join_class_name_str = '暂无';
        }
        $data['join_class_name'] = $join_class_name_str;
        $data['join_class'] = $join_class;


        //本班学员110
        $data['formal_students_count'] = $this->getFormalStudentsCountByCourseid($course_id);

        //非本班学员100，102，103
        $data['noclass_formal_students_count'] = $this->getNoclassFormalStudentsCountByCourseid($course_id);

        /*//审核通过会员或者老学员 001，101
        $data['pass_user_count'] = $this->getPassUserCountByCourseid($course_id);

        //审核未通过会员002
        $data['nopass_user_count'] = $this->getNoPassUserCountByCourseid($course_id);

        //未申请会员003
        $data['noapply_user_count'] = $this->getNoApplyUserCountByCourseid($course_id);*/

        $data['bought_count'] = $this->getBoughtCourseUserCount($course_id, $sid);


        return $data;
    }

    /**
     *  获取课程本班正式学员人数
     * @param $course_id
     * @return int|string
     */
    public function getFormalStudentsCountByCourseid($course_id){
        //本班学员110
//        return db('course_students')->where(['courseid' => $course_id, 'formal_status'=>1, 'ourclass_status'=>1])->count();
        $course_class = db('course_class')->where(['courseid' => $course_id])->select();
        $class_ids = [];
        if($course_class){
            foreach($course_class as $k => $v){
                $class_ids[$k] = $v['classid'];
            }
            return db('class_students')->where(['classid' => ['in', $class_ids]])->count();
            //return db('class_students')->where(['classid' => ['in', $class_ids], 'formal_status' => 1])->count();
        } else {
            return 0;
        }

    }

    public function getFormalStudentsListByCourseid($course_id, $p, $pageSize){
        $data = [];
        $course_class = db('course_class')->where(['courseid' => $course_id])->select();
        $class_ids = [];
        if($course_class){
            foreach($course_class as $k => $v){
                $class_ids[$k] = $v['classid'];
            }
            $list = db('class_students')->field('studentsid')->where(['classid' => ['in', $class_ids]])->select();
            $student_ids = [];
            if($list){
                foreach($list as $k => $v){
                    if($v['studentsid']){
                        $student_ids[$k] = $v['studentsid'];
                    }
                }
                $student_ids = array_unique($student_ids);
            }
//            $students_field = 'st.uid,st.name,st.phone,st.cardid,st.company,st.business,st.birthday,st.life_motto,u.user_nickname,u.user_headimgurl,cs.attend_status,cs.sign_status';
            $students_field = 'st.id,st.uid,st.name,st.phone,st.cardid,st.company,st.business,st.birthday,st.life_motto,u.user_nickname,u.user_headimgurl';

            if($student_ids){
                $data = db('students st')
                    ->field($students_field)
                    ->join('user u', 'st.uid = u.user_id', 'LEFT')
//                    ->join('course_students cs', 'st.id = cs.studentsid', 'LEFT')
                    ->where(['st.id' => ['in', $student_ids]])
                    ->order('st.uid DESC,st.id DESC')
                    ->limit(($p-1) * $pageSize, $pageSize)
                    ->select();
            }

            $course_students = db('course_students')->field('uid,studentsid,attend_status,sign_status')->where(['courseid' => $course_id])->select();
            //将uid变为数组索引
            foreach($course_students as $k1 => $v1){
                $temp[$v1['uid']] = $v1;
            }

            if($data){
                foreach($data as $key => $val){
                    if(isset($temp[$val['uid']])){
                        $data[$key]['attend_status'] = $temp[$val['uid']]['attend_status'];
                        $data[$key]['sign_status'] = $temp[$val['uid']]['sign_status'];
                    } else {
                        $data[$key]['attend_status'] = 0;
                        $data[$key]['sign_status'] = 0;
                    }
                }
            }
        }
        return $data;
    }

    /**
     *  获取课程已签到本班正式学员人数
     * @param $course_id
     * @return int|string
     */
    public function getSignedFormalStudentsCountByCourseid($course_id){
        //本班学员110
        return db('course_students')->where(['courseid' => $course_id, 'formal_status'=>1, 'ourclass_status'=>1,'sign_status' => 1])->count();
    }

    /**
     *  获取课程非本班正式学员人数
     * @param $course_id
     * @return int|string
     */
    public function getNoclassFormalStudentsCountByCourseid($course_id){
        //非本班学员100，102，103
        return db('course_students')->where(['courseid' => $course_id, 'formal_status'=>1, 'ourclass_status'=>0,'apply_status'=>['neq',1]])->count();
    }
    /**
     *  获取课程审核通过会员人数
     * @param $course_id
     * @return int|string
     */
    public function getPassUserCountByCourseid($course_id){
        //审核通过会员或者老学员001，101
        return db('course_students')->where(['courseid' => $course_id,  'ourclass_status'=>0, 'apply_status'=>1])->count();
    }
    /**
     *  获取课程审核未通过会员人数
     * @param $course_id
     * @return int|string
     */
    public function getNoPassUserCountByCourseid($course_id){
        //审核未通过会员002
        return db('course_students')->where(['courseid' => $course_id, 'formal_status'=>0, 'ourclass_status'=>0, 'apply_status'=>2])->count();
    }
    /**
     *  获取课程未申请会员人数
     * @param $course_id
     * @return int|string
     */
    public function getNoApplyUserCountByCourseid($course_id){
        //未申请会员003
        return db('course_students')->where(['courseid' => $course_id, 'formal_status'=>0, 'ourclass_status'=>0, 'apply_status'=>3])->count();
    }

    /**
     *  获取课程应签到人数
     * @param $course_id
     * @return int|string
     */
    public function getSignCountByCourseid($course_id){
        //本班学员110，申请通过会员001，申请通过老会员101
        $format =  $this->getFormalStudentsCountByCourseid($course_id);
        $apply = $this->getPassUserCountByCourseid($course_id);
        return $format+$apply;
    }

    /**
     *  获取课程实签到人数
     * @param $course_id
     * @return int|string
     */
    public function getSignedCountByCourseid($course_id){
        return db('course_students')->where(['courseid' => $course_id,'sign_status' => 1 ])->count();
    }

    /**
     * 获取课程申请试听成功的试听学员人数
     * @param $course_id
     * @return int|string
     */
    public function getSignedListeningStudentsCountByCourseid($course_id){
        return db('course_students')->where(['courseid' => $course_id, 'sign_status' => 1, 'ourclass_status' => 0, 'apply_status' => 1])->count();
    }

    /**
     * 获取班级详情会员列表
     * @param $sid
     * @param $course_id
     * @param $type
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getCourseDetailStudentsAdmin($sid, $course_id, $type, $p, $pageSize){
        //查询字段
        $students_field = 'cr.courseid,st.uid,st.name,st.phone,st.cardid,st.company,st.business,st.birthday,st.life_motto,u.user_nickname,u.user_headimgurl,cs.attend_status,cs.sign_status';

        /*if($type == 1){
            //本班学员110
//            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.formal_status'=>1,'cs.ourclass_status'=>1], $students_field, $p, $pageSize);
            $students_list = $this->getFormalStudentsListByCourseid($course_id, $p, $pageSize);
            $count = $this->getFormalStudentsCountByCourseid($course_id);
        } elseif ($type == 2){
            //非本班学员100，102，103
            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.formal_status'=>1,'cs.ourclass_status'=>0,'cs.apply_status'=>['neq',1]], $students_field, $p, $pageSize);
            $count = $this->getNoclassFormalStudentsCountByCourseid($course_id);

        } elseif ($type == 3){
            //审核通过会员或老学员 001，101
            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.ourclass_status'=>0,'cs.apply_status'=>1], $students_field, $p, $pageSize);
            $count = $this->getPassUserCountByCourseid($course_id);

        } elseif ($type == 4){
            //审核未通过会员002
            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.formal_status'=>0,'cs.ourclass_status'=>0,'cs.apply_status'=>2], $students_field, $p, $pageSize);
            $count =  $this->getNoPassUserCountByCourseid($course_id);

        } elseif ($type == 5){
            //未申请会员003
            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.formal_status'=>0,'cs.ourclass_status'=>0,'cs.apply_status'=>3], $students_field, $p, $pageSize);
            $count =  $this->getNoApplyUserCountByCourseid($course_id);

        }*/
        if($type == 1){
            //本班学员110
//            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.formal_status'=>1,'cs.ourclass_status'=>1], $students_field, $p, $pageSize);
            $students_list = $this->getFormalStudentsListByCourseid($course_id, $p, $pageSize);
            $count = $this->getFormalStudentsCountByCourseid($course_id);
        } elseif ($type == 2){
            //非本班学员100，102，103
            $students_list = $this->getStudents(['cr.courseid' => $course_id,'cs.formal_status'=>1,'cs.ourclass_status'=>0,'cs.apply_status'=>['neq',1]], $students_field, $p, $pageSize);
            $count = $this->getNoclassFormalStudentsCountByCourseid($course_id);

        } elseif ($type == 3){
            //已购买此课程的学员
            $students_list = $this->getBoughtCourseUserList($course_id, $sid, $p, $pageSize);
            $count = $this->getBoughtCourseUserCount($course_id, $sid);

        }

        //反序列化学生公司信息
        if($students_list){
            foreach ($students_list as $key => $val)
                if($val['company']){
                    //unserialize():Error at offset
                    //当我们取出数据库编码为GBK等中文编码，后又用转码函数转成UTF8后，再用unserialize函数时，因为中文在不同编码下的长度不同，就会出现这个问题了。
                    //解决方案1：unserialize(preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $string))
                    //解决方案2：由于php的原因，/e 模式存在漏洞，所以php5.5以后取消了这样的用法
                    //preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';},$data);

//                    $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $val['company']);
//                    $students_list[$key]['company'] = unserialize($temp);
                    $students_list[$key]['company'] = Util::unserializeStr($val['company']);

//                    $students_list[$key]['company'] = unserialize($val['company']);

                }
        }

        $data['content'] = $students_list;
        $data['page']['count'] = $count;

        return $data;
    }


    /**
     * 获取某课程学生相关信息
     * @param array $condition
     * @param $filed
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getStudents($condition = [], $filed, $p, $pageSize){
        $list = db()->name('course cr')
                ->field($filed)
                ->join('course_students cs', 'cs.courseid = cr.courseid', 'LEFT')
                ->join('user u', 'u.user_id = cs.uid', 'LEFT')
                ->join('students st', 'st.uid = u.user_id', 'LEFT')
                ->where($condition)
                ->order('cr.courseid DESC')
                ->limit(($p-1) * $pageSize, $pageSize)
                ->select();
        if($list){
            foreach ($list as $k => $v){
                //处理cardid字段
//                $list[$k]['cardid'] = strlen($v['cardid']) == 15 ? substr_replace($v['cardid'],"************",3,12) : (strlen($v['cardid']) == 18 ? substr_replace($v['cardid'],"***************",3,15) :"暂未提供");
                //处理班级
                $classes = db()->name('class_students')
                            ->alias('cs')
                            ->field('c.name')
                            ->join('classes c', 'c.classid = cs.classid', 'LEFT')
                            ->where(['cs.uid' => $v['uid']])
                            ->select();
                $class_list = [];
                if(!empty($classes)){
                    foreach($classes as $vo){
                        $class_list[]=$vo['name'];
                    }
                }
                $list[$k]['class_info'] =implode(',', $class_list);
            }
        }
        return $list;
    }

    /**
     * 发起试听
     * @param $sid
     * @param $course_id
     * @param $deadline
     * @return array
     * @throws \think\Exception
     */
    public function startCourseListening($sid, $course_id, $deadline){
        $deadline = strtotime($deadline);
        $schoolovertime = db('course')->where(['courseid' => $course_id, 'sid' => $sid])->value('schoolovertime');
        if($schoolovertime < $deadline){
            return ['status' => 0, 'msg' => '申请截止时间不能大于课程结束时间'];
        }

        $result = db('course')->where(['courseid' => $course_id, 'sid' => $sid])->update(['status' => 1, 'deadline' => $deadline]);
        return $result === false ? ['status' => 0, 'msg' => '发起试听失败'] : ['status' => 1, 'msg' => '发起试听成功'];
    }


    /**
     * 获取课程试听列表
     * @param $sid
     * @param $course_id
     * @param $type
     * @param $search
     * @param $p
     * @param $pageSize
     */
    public function getCourseListeningList($sid, $type, $search, $p, $pageSize){
        $data = [];

        $condition = [];
        $condition['cli.sid'] = $sid;
        if(!empty($search)){
            $condition['cr.name|cr.speaker'] = '%'.$search.'%';
        }
        switch ($type) {
            case 1:
                break;
            case 2:
                $condition['cli.status'] = 0;
                break;
            case 3:
                $condition['cli.status'] = 1;
                break;
            case 4:
                $condition['cli.status'] = 2;
                break;
            default:
                break;
        }
//        $count = $this->getCourseListeningCount($condition);

        $field = 'cli.*,cr.name as course_name,cr.speaker,cr.pic,st.name as student_name,st.phone,st.company';
        $list = db()->name('course_listening cli')
                ->field($field)
                ->join('course cr', 'cr.courseid = cli.courseid', 'LEFT')
                ->join('students st', 'st.uid = cli.uid', 'LEFT')
                ->where($condition)
                ->order('cli.id DESC')
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();
        if($list){
            foreach ($list as $k => $v){
//                $list[$k]['company'] = unserialize($v['company']);
//                $temp = preg_replace_callback('#s:(\d+):"(.*?)";#s',function($match){return 's:'.strlen($match[2]).':"'.$match[2].'";';}, $v['company']);
//                $list[$k]['company'] = unserialize($temp);
                $list[$k]['company'] = Util::unserializeStr($v['company']);
                $list[$k]['apply_time'] = date('Y-m-d H:i:s', $v['apply_time']);
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
                if($v['checked_time'] > 0){
                    $list[$k]['checked_time'] = date('Y-m-d H:i:s', $v['checked_time']);
                }
            }
        }

        $data['content'] = $list;

        //所有审核数量
        $data['page']['all_count'] = db('course_listening')->where(['sid' => $sid])->count();
        //未审核数量
        $data['page']['unchecked_count'] = db('course_listening')->where(['sid' => $sid, 'status' => 0])->count();
        //已通过审核数量
        $data['page']['pass_count'] = db('course_listening')->where(['sid' => $sid, 'status' => 1])->count();
        //已拒绝审核数量
        $data['page']['refuse_count'] = db('course_listening')->where(['sid' => $sid, 'status' => 2])->count();

        //当前值
        if($type == 1){
            $data['page']['count'] = $data['page']['all_count'];
        } elseif ($type == 2){
            $data['page']['count'] = $data['page']['unchecked_count'];
        } elseif ($type == 3){
            $data['page']['count'] = $data['page']['pass_count'];
        } elseif ($type == 4){
            $data['page']['count'] = $data['page']['refuse_count'];
        }

        return $data;
    }

    /**
     * 获取课程试听审核列表总数
     * @param array $condition
     * @return int|string
     */
    public function getCourseListeningCount($condition = []){
        $count = db()->name('course_listening cli')
                ->join('course cr', 'cr.courseid = cli.courseid', 'INNER')
                ->join('students st', 'st.uid = cli.uid', 'INNER')
                ->where($condition)
                ->count();
        return $count;
    }


    /**
     * 试听申请审核
     * @param $sid
     * @param $course_listening_id
     * @param $type
     * @return array
     * @throws \think\Exception
     */
    public function changeCourseListening($sid, $course_listening_id, $type){
        $data = [];
        $data['checked_time'] = time();//审核时间

        $condition = [];

        switch ($type) {
            case 'pass':
                $condition['id'] = $course_listening_id;
                $data['status'] = 1;
                break;
            case 'refuse':
                $condition['id'] = $course_listening_id;
                $data['status'] = 2;
                break;
            case 'pass_all':
                $condition['id'] = ['in',$course_listening_id];
                $data['status'] = 1;
                break;
            case 'refuse_all':
                $condition['id'] = ['in',$course_listening_id];
                $data['status'] = 2;
                break;
            default:
                break;
        }

        if($type == 'pass'){
            $course_listening = db('course_listening')->where(['sid' => $sid, 'id' => $course_listening_id])->find();
            if($course_listening){
                $add_data = [];
                $add_data['uid'] = $course_listening['uid'];
                $add_data['sid'] = $sid;
                $add_data['courseid'] = $course_listening['courseid'];
                $add_data['addtime'] = time();
                //是否为学员
                $class_students_info = db('class_students')->where(['uid' => $course_listening['uid']])->find();
                $add_data['formal_status'] = $class_students_info ? 1 : 0;
                $add_data['ourclass_status'] = 0;
                $add_data['apply_status'] = 1;
                $add_data['studentsid'] = db('students')->where(['uid' => $course_listening['uid'], 'sid' => $sid])->value('id');
                //加入到course_studetns表中
                $r = db('course_students')->insert($add_data);
                if($r === false){
                    return ['status' => 0, 'msg' => '操作失败'];
                }
            }
        }

        if($type == 'pass_all'){
            if(!is_array($course_listening_id) || count($course_listening_id) < 1){
                return ['status' => 0, 'msg' => '批量参数错误'];
            }
            $course_listening_all = db('course_listening')->where(['sid' => $sid, 'id' => ['in', $course_listening_id]])->select();
            if($course_listening_all){
                $add_data = [];

                foreach($course_listening_all as $k => $v){
                    $add_data[$k]['uid'] = $v['uid'];
                    $add_data[$k]['sid'] = $sid;
                    $add_data[$k]['courseid'] = $v['courseid'];
                    $add_data[$k]['addtime'] = time();
                    //是否为学员
                    $class_students_info = db('class_students')->where(['uid' => $v['uid']])->find();
                    $add_data[$k]['formal_status'] = $class_students_info ? 1 : 0;
                    $add_data[$k]['ourclass_status'] = 0;
                    $add_data[$k]['apply_status'] = 1;
                    $add_data[$k]['studentsid'] = db('students')->where(['uid' => $v['uid'], 'sid' => $sid])->value('id');
                }
                //加入到course_studetns表中
                $r = db('course_students')->insertAll($add_data);
                if($r === false){
                    return ['status' => 0, 'msg' => '操作失败'];
                }
            }
        }

        //发送消息模版，通过才发送
        if($type == 'pass' || $type == 'pass_all'){
            $wxTplService = new WxTplMsgService();
            $wxTplService->send($sid, $course_listening_id, 'course_packet');
        }

        $res = db('course_listening')->where($condition)->update($data);

        return $res === false ? ['status' => 0, 'msg' => '操作失败！'] : ['status' => 1, 'msg' => '操作成功！'];
    }


    /**
     * 导出课程试听学员
     * @param $sid
     * @param $course_id
     * @return bool
     */
    public function exportCourseListeningStudents($sid, $course_id){
        $students_field = 'cr.courseid,cr.name as course_name,st.uid,st.name,st.phone,st.cardid,st.company,st.business,u.user_nickname,u.user_headimgurl,cs.attend_status';
        $where = [];
        $where['cr.courseid'] = $course_id;
        $where['cr.sid'] = $sid;
        $list = db()->name('course cr')
                ->field($students_field)
                ->join('course_students cs', 'cs.courseid = cr.courseid')
                ->join('user u', 'u.user_id = cs.uid')
                ->join('students st', 'st.uid = u.user_id')
                ->where($where)
                ->order('cr.courseid DESC')
                ->select();

        $down_array[1] = [
            'A1' => '姓名',
            'B1' => '联系方式',
            'C1' => '公司',
            'D1' => '主营业务',
        ];

//        if(empty($list)){
//            return false;
//        }

        //内容设置
        foreach($list as $k1 => $v1){
            $key = $k1+2;
            if(!empty($v1['company'])){
//                $company = unserialize($v1['company']);
                $company = Util::unserializeStr($v1['company']);
                if(!empty($company) && is_array($company)){
                    $company_array = [];
                    foreach($company as $val){
                        $company_array[]=$val['cname'].'/'.$val['position'].'/'.$val['address'];
                    }
                    $company_string = implode(',',$company_array);
                }else{
                    $company_string = '未完善';
                }
            }else{
                $company_string = '未完善';
            }
            $down_array[$key] = [
                'A'.$key => $v1['name'],
                'B'.$key => $v1['phone'],
                'C'.$key => $company_string,
                'D'.$key => $v1['business'],
            ];
        }

        if($list){
            $filename = $list[0]['course_name'].'_试听' . date('YmdHis') . '.xlsx'; //设置文件名
        } else {
            $course_name = db('course')->where(['courseid' => $course_id])->value('name');
            $filename = $course_name.'_试听' . date('YmdHis') . '.xlsx';
        }

        ExcelHelper::down($filename, $down_array, 'courseListeningStudents');
        return true;
    }


    /**
     * 导出已购买课程学员
     * @param $sid
     * @param $course_id
     * @return bool
     */
    public function exportCourseBoughtStudents($sid, $course_id){
        $students_field = 'cr.courseid,cr.name as course_name,st.uid,st.name,st.phone,st.cardid,st.company,st.business,u.user_nickname,u.user_headimgurl,ui.counselor_id';
        $where = [
            'oc.course_id' => $course_id,
            'oc.sid' => $sid,
            'o.status' => 1
        ];
        $list = db('order_course oc')
                ->field($students_field)
                ->join('order o', 'o.order_id=oc.order_id')
                ->join('course cr', 'cr.courseid=oc.course_id')
                ->join('user u', 'u.user_id=oc.buyer_id')
                ->join('user_integral ui', 'ui.userid=oc.buyer_id')
                ->join('students st', 'st.uid=oc.buyer_id')
                ->where($where)
                ->order('cr.courseid DESC')
                ->select();

        $down_array[1] = [
            'A1' => '姓名',
            'B1' => '联系方式',
            'C1' => '公司',
            'D1' => '顾问',
        ];

//        if(empty($list)){
//            return false;
//        }

        //内容设置
        foreach($list as $k1 => $v1){
            //获取顾问名称
            $counselor_name = db('user_integral ui')
                                ->join('user u', 'ui.userid=u.user_id')
                                ->where(['ui.userid' => $v1['counselor_id']])
                                ->value('u.user_name');

            $key = $k1+2;
            if(!empty($v1['company'])){
//                $company = unserialize($v1['company']);
                $company = Util::unserializeStr($v1['company']);
                if(!empty($company) && is_array($company)){
                    $company_array = [];
                    foreach($company as $val){
                        $company_array[]=$val['cname'].'/'.$val['position'].'/'.$val['address'];
                    }
                    $company_string = implode(',',$company_array);
                }else{
                    $company_string = '未完善';
                }
            }else{
                $company_string = '未完善';
            }
            $down_array[$key] = [
                'A'.$key => $v1['name'],
                'B'.$key => $v1['phone'],
                'C'.$key => $company_string,
                'D'.$key => $counselor_name,
            ];
        }

        if($list){
            $filename = $list[0]['course_name'].'_购买' . date('YmdHis') . '.xlsx'; //设置文件名
        } else {
            $course_name = db('course')->where(['courseid' => $course_id])->value('name');
            $filename = $course_name.'_购买' . date('YmdHis') . '.xlsx';
        }

        ExcelHelper::down($filename, $down_array, 'courseBoughtStudents');
        return true;
    }


    /**
     * 发送课程开课提醒
     * @param $sid
     * @param $course_id
     * @return bool
     */
    public function sendCourseRemind($sid, $course_id){
        $list = db('course_students cs')
                ->field('u.user_id,u.user_openid')
                ->join('user u', 'cs.uid = u.user_id')
                ->where(['cs.courseid' => $course_id, 'cs.sid' => $sid])
                ->select();

        if(empty($list)){
            return ['status' => 0, 'msg' => '当前课程学员为空'];
        }

        $opend_ids = [];
        foreach($list as $k => $v){
            $opend_ids[$k] = $v['user_openid'];
        }

        $wxTplMsgService = new WxTplMsgService();

        $result = $wxTplMsgService->send($sid, $course_id, 'course_begin', $opend_ids);
        return $result == true ? ['status' => 1, 'msg' => '发送成功'] : ['status' => 0, 'msg' => '发送失败'];
    }

    /**
     * 下载签到学员
     * @param $sid
     * @param $courseid
     * @return array
     */
    public function exportSignStudents($sid,$courseid){
        $course_name = db('course')->where(['courseid' => $courseid])->value('name');
        if(empty($course_name)){
            return ['status' => 0,'msg' => '未查询到课程'];
        }
        $where = [
            'cs.sign_status' => 1,
            'cs.sid' => $sid,
            'cs.courseid' => $courseid
        ];
        $field = 's.name,s.phone,s.company,s.uid,cs.apply_status,cs.formal_status,cs.ourclass_status,cs.addtime,cs.sign_type';
        $list = db('course_students cs')
            ->join('students s','cs.uid = s.uid and cs.sid = s.sid')
            ->where($where)
            ->field($field)
            ->select();
//        if(empty($list)){
//            return ['status' => 0,'msg' => '未查询到客户'];
//        }
        //头部设置

        $down_array[1] = [
            'A1' => '姓名',
            'B1' => '联系方式',
            'C1' => '公司',
            'D1' => '身份',
            'E1' => '签到时间',
            'F1' => '签到类型'
        ];

        //内容设置
        foreach($list as $k => $v){
            $key = $k+2;
            if(!empty($v['company'])){
//                $company = unserialize($v['company']);
                $company = Util::unserializeStr($v['company']);
                $company_array = array();
                if(!empty($company) && is_array($company)){
                    foreach($company as $val){
                        $company_array[]=$val['cname'].'/'.$val['position'].'/'.$val['address'];
                    }
                    $company_string = implode(',',$company_array);
                }else{
                    $company_string = '未完善';
                }
            }else{
                $company_string = '未完善';
            }

            /*if($v['ourclass_status'] == 1){
                $identity  = '本班学员';
            }else{
                if($v['formal_status'] == 1){
                    $identity = '老学员';
                }else{
                    if($v['apply_status'] == 1){
                        $identity = '试听会员';
                    }else{
                        $identity = '其他';
                    }
                }
            }*/
            if($v['formal_status'] == 1){
                if($v['ourclass_status'] == 1){
                    $identity = '本班学员';
                } else {
                    $class_ids = db('course_class')->where(['courseid' => $courseid])->column('classid');
                    $class_student = db('class_students')->where(['uid' => $v['uid'], 'classid' => ['in', $class_ids]])->find();
                    $identity = $class_student ? '本班学员' : '非本班学员';
                }
            } else {
                $identity = '其他';
            }

            //签到类型
            if($v['sign_type'] == 1){
                $sign_type = '扫码签到';
            } elseif($v['sign_type'] == 2){
                $sign_type = '人脸签到';
            } elseif($v['sign_type'] == 3){
                $sign_type = '二维码核验签到';
            }

            $down_array[$key] = [
                'A'.$key => $v['name'],
                'B'.$key => $v['phone'],
                'C'.$key => $company_string,
                'D'.$key => $identity,
                'E'.$key => date('Y-m-d H:i:s', $v['addtime']),
                'F'.$key => $sign_type
            ];
        }
        $filename = $course_name.'签到情况.xlsx';
        ExcelHelper::down($filename,$down_array,'signStudentList');
        return ['status' =>1, 'msg' => '导出成功'];
    }


    /**
     * 微信端获取模版店铺课程库详情
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return array
     */
    public function getCourseLibraryDetail($sid, $uid, $course_id){
        //判断是否为管理员
        $user = db('user_integral')->where(['userid' => $uid, 'sid' => $sid])->find();
        if($user['is_administrator'] != 1){
            return ['status' => 0, 'msg' => '非法请求'];
        }

        $course_detail = $this->getCourseDetail($course_id);
        if($course_detail['sid'] != config('template_sid') || $course_detail['release_status'] == 0 || $course_detail['course_status'] == -1){
            return ['status' => 0, 'msg' => '课程信息不存在'];
        }

        //判断自身店铺是否引入
        $self_course = db('course')->where(['sid' => $sid, 'origin_courseid' => $course_id, 'course_status' => ['<>', -1]])->find();
        $course_detail['is_quote'] = $self_course ? 1 : 0;
        if($self_course){
            $course_detail['quote_courseid'] = $self_course['courseid'];
        }

        return ['status' => 1, 'msg' => '获取成功', 'data' => $course_detail];
    }


    /**
     * 获取未开始的课程列表
     * @param $sid
     * @return mixed
     */
    public function getUnstartCourseList($sid, $p, $pageSize){
        $where = [
            'sid' => $sid,
            'schooltime' => ['>', time()],
            'course_status' => 1
        ];
        $field = 'courseid,name,speaker,schooltime,pic';
        $list = db('course')
                ->field($field)
                ->where($where)
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->order('schooltime ASC')
                ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['schooltime'] = date('Y-m-d H:i:s', $v['schooltime']);
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
            }
        }
        return $list;
    }

    /**
     * 微信端: 顾问获取未开始的课程列表
     * @param $sid
     * @param $uid
     * @return array|mixed
     */
    public function getUnstartCourseListByCounselor($sid, $uid, $p, $pageSize){
        $is_counselor = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        if($is_counselor != 1){
            return ['status' => 0, 'msg' => '用户信息有误'];
        }
        $list = $this->getUnstartCourseList($sid, $p, $pageSize);
        $data = ['data' => $list, 'status' => 1,'msg' => '获取成功'];
        return $data;
    }


    /**
     * 微信端: 获取课程海报
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return array
     */
    public function getCoursePosters($sid, $uid, $course_id){
        $is_counselor = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        if($is_counselor != 1){
            return ['status' => 0, 'msg' => '用户信息有误'];
        }

        $course = db('course')->where(['sid' => $sid, 'courseid' => $course_id, 'course_status' => 1])->find();
        if(!$course){
            return ['status' => 0, 'msg' => '课程不存在'];
        }

        if(!$course['poster_imgs']){
            return ['status' => 0, 'msg' => '未设置海报'];
        }

        $posters = json_decode($course['poster_imgs'], 1);

        //查询是否生成过带参二维码
       /* $qrcode_url = db('counselor_course_qrcode')->where(['uid' => $uid, 'courseid' => $course_id])->value('qrcode_url');
        if($qrcode_url){
            $wxService = new WeixinService();
            $key = 'qrscene_user_'.$uid.'&qrscene_course_'.$course_id;
            $qrcode = $wxService->get_forever_qrcode($sid, $key);
            $qrcode_url = $qrcode['qrcode_url'];
            db('counselor_course_qrcode')->insert(['uid' => $uid, 'courseid' => $course_id, 'qrcode_url' => $qrcode_url]);
        }*/
        $qrcode_url = CoursePosterHelper::getCourseDetailQrcode($sid, $uid, $course_id);
        $data = $this->buildCoursePosters($uid, $course_id, $posters, $qrcode_url);

        return ['status' => 1, 'data' => $data, 'msg' => '获取成功'];
    }


    /**
     * 微信端: 根据用户ID、课程ID生成课程海报
     * @param $uid
     * @param $course_id
     * @param array $posters
     * @param $qrcode_url
     * @return array|bool
     */
    public function buildCoursePosters($uid, $course_id, $posters = [], $qrcode_url){
        //默认图片宽高为 720 * 1280

        /**
         * 二维码
         * 左上角：X：511   Y:1024
         * 右上角：X：681   Y:1024
         * 左下角：X：511   Y:1193（1194）
         * 右下角：X：681   Y:1193（1194）
         * 大小170x169（170）
         *
         */

        //判断尺寸是否符合要求
        foreach($posters as $k => $v){
            list($poster_w, $poster_h) = getimagesize($v);
            //图片比例9:16
            if($poster_w * 16 != $poster_h * 9){
                unset($posters[$k]);
            }
        }
        if(!$posters){
            return false;
        }

        $coursePosterHelper = new CoursePosterHelper();
        $data = $coursePosterHelper->createPosters($uid, $course_id, $qrcode_url, $posters);
        foreach($data as $k => $v){
            $data[$k] = $this->domain.$v;
        }
        return $data;
    }


    /**
     * 将之前主讲人字段由字符串替换为json对象，保存
     * @return bool
     */
    public function changeSpeaker(){
        $list = db('course')->field('courseid,speaker')->select();
        foreach($list as $k => $v){
            if(!Util::isJson($v['speaker'])){
                $speaker = [];
                $speaker[0]['speaker_name'] = $v['speaker'];
                $speaker[0]['speaker_intro'] = '';
                $speaker[0]['speaker_avatar'] = '';
                $r = db('course')->where(['courseid' => $v['courseid']])->setField('speaker', json_encode($speaker, JSON_UNESCAPED_UNICODE));
                if(!$r){
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 微信端: 获取所有课程列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getAllCourseList($sid, $p, $pageSize){
        $where = [
            'sid' => $sid,
            'course_status' => 1
        ];
        $field = 'courseid,name,speaker,content,schooltime,schoolovertime,pic';
        $list = db('course')
            ->field($field)
            ->where($where)
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->order('addtime DESC')
            ->select();

        if($list){
            $cur_time = time();
            foreach($list as $k => $v){
                $list[$k]['schooltime'] = date('Y-m-d H:i:s', $v['schooltime']);
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
            }
        }
        return $list;
    }


    /**
     * 微信端: 获取班级课程列表
     * @param $sid
     * @param $class_id
     * @param $p
     * @param $pageSize
     */
    public function getListByClassId($sid, $class_id, $p, $pageSize){
        $where = [
            'c.sid' => $sid,
            'c.course_status' => 1,
            'cc.classid' => $class_id
        ];
        $field = 'c.courseid,c.name,c.speaker,c.content,c.schooltime,c.schoolovertime,c.pic';
        $list = db('course_class cc')
                ->field($field)
                ->join('course c', 'c.courseid=cc.courseid')
                ->where($where)
                ->limit(($p - 1) * $pageSize, $pageSize)
                ->order('c.addtime DESC')
                ->select();


        if($list){
            $cur_time = time();
            foreach($list as $k => $v){
                $list[$k]['schooltime'] = date('Y-m-d H:i:s', $v['schooltime']);
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
                if($cur_time < $v['schooltime']){
                    $list[$k]['process_status'] = 1; //未开始
                } elseif ($cur_time > $v['schoolovertime']){
                    $list[$k]['process_status'] = 3; //已结束
                } else{
                    $list[$k]['process_status'] = 2; //进行中
                }
            }
        }
        return $list;
    }


    /**
     * 微信端: 获取课程基本详情
     * @param $course_id
     * @return array|bool
     */
    public function getCourseBaseDetail($course_id){
        $field = 'courseid,name,speaker,schooltime,schoolovertime,description,content,pic,stock,course_price,is_allow_coupon,poster_imgs,
        is_allow_buy,payment_type,need_avatar,course_status';
        $course_detail = $this->getCourseDetail($course_id, $field);
        $course_detail['schooltime'] = date('n月d日 H:i', $course_detail['schooltime']);
        $course_detail['schoolovertime_str'] = date('n月d日 H:i', $course_detail['schoolovertime']);
        $course_detail['poster_imgs'] = $course_detail['poster_imgs'] ? json_decode($course_detail['poster_imgs'], 1) : '';
        $course_detail['payment_type'] = $course_detail['payment_type'] ? explode(',', $course_detail['payment_type']) : '';
        return $course_detail;
    }

    /**
     * 后台: 是否开启课程智能推送
     * @param $sid
     * @param $course_id
     * @param $start_intelligent_push
     * @return int
     */
    public function isStartIntelligentPush($sid, $course_id, $start_intelligent_push)
    {
        return db('course')
            ->where(['courseid' => $course_id, 'sid' => $sid, 'course_status' => 1])
            ->setField('start_intelligent_push', $start_intelligent_push);
    }


    /**
     * 后台: 课程购买设置
     * @param $sid
     * @param array $postParam
     * @return array
     * @throws \think\Exception
     */
    public function buySetting($sid, $postParam = []){
        $info = db('course')
                ->where([
                    'sid' => $sid,
                    'courseid' => $postParam['course_id'],
                    'schoolovertime' => ['>', time()],
                    'course_status' => ['<>', -1]
                ])
                ->find();
        if(!$info){
            return ['status' => 0, 'msg' => '未找到相关课程'];
        }
        $apply_deadline = strtotime($postParam['apply_deadline']);
        if($apply_deadline > $info['schoolovertime']){
            return ['status' => 0, 'msg' => '您设置的时间已经超过课程结束时间，请重新设置'];
        }

        $update_data = [
            'course_price' => $postParam['course_price'],
            'stock' => $postParam['stock'],
            'apply_deadline' => $apply_deadline,
            'is_allow_buy' => $postParam['is_allow_buy'],
            'is_allow_coupon' => $postParam['is_allow_coupon'],
            'payment_type' => implode(',', $postParam['payment_type']),
            'need_avatar' => $postParam['need_avatar']
        ];

        $r = db('course')->where(['courseid' => $postParam['course_id']])->update($update_data);
        return $r === false ? ['status' => 0, 'msg' => '设置失败'] : ['status' => 1, 'msg' => '设置成功'];
    }

    /**
     * 微信端: 获取商城课程列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getShoppingCourseList($sid, $course_id = 0, $p, $pageSize){
        $where = [
            'sid' => $sid,
            'schoolovertime' => ['>', time()],
            'is_allow_buy' => 1,
            'course_status' => 1
        ];
        if($course_id){
            $where['courseid'] = ['<>', $course_id];
        }
        $field = 'courseid,name,speaker,schooltime,pic,course_price,is_allow_coupon,poster_imgs';
        $list = db('course')
                ->field($field)
                ->where($where)
                ->order('schooltime ASC')
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->select();
        if($list){
            foreach ($list as $k => $v) {
                $list[$k]['speaker'] = json_decode($v['speaker'], 1);
                $list[$k]['schooltime'] = date('Y-m-d H:i:s', $v['schooltime']);
                $list[$k]['poster_imgs'] = $v['poster_imgs'] ? json_decode($v['poster_imgs'], 1) : '';
            }
        }
        return $list;
    }

    /**
     * 微信端: 判断用户是否购买了此课程
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return bool
     */
    public function isBuyCourse($sid, $uid, $course_id){
        $is_counselor = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('counselor_status');
        //顾问返回已购买状态
        if($is_counselor){
            return 1;
        }

        //查询是否属于自身的正式课程
        //课程相关的班级
        $course_class = db('course_class')->field('classid')->where(['courseid' => $course_id])->select();
        $course_class_ids = [];
        if($course_class){
            foreach($course_class as $k => $v){
                $course_class_ids[$k] = $v['classid'];
            }
        }

        //自身班级
        $class_students = db('class_students')->field('classid')->where(['uid' => $uid, 'sid' => $sid])->select();
        $own_class_id = [];
        if($class_students){
            foreach($class_students as $key => $val){
                $own_class_id[$key] = $val['classid'];
            }
        }

        if(array_intersect($own_class_id, $course_class_ids)){
            return 1;
        }

        $where = [
            'oc.sid' => $sid,
            'oc.buyer_id' => $uid,
            'oc.course_id' => $course_id,
            'o.status' => ['in', [1,5]]  //1完成支付,5线下支付待确认状态
        ];
        $result = db('order_course oc')
                ->join('order o', 'oc.order_id=o.order_id')
                ->where($where)
                ->find();
        return $result['status'] == 5 ? 2 : ($result['status'] == 1 ? 1 : 0);
    }


    /**
     * 获取已购买某课程的学员列表
     * @param $course_id
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return mixed
     */
    public function getBoughtCourseUserList($course_id, $sid, $p, $pageSize){
        $filed = 'cr.courseid,st.uid,st.name,st.phone,st.cardid,st.company,st.business,st.birthday,st.life_motto,u.user_nickname,u.user_headimgurl,cs.attend_status,cs.sign_status';
        $condition = [
            'oc.course_id' => $course_id,
            'oc.sid' => $sid,
            'o.status' => 1
        ];
        $list = db('order_course oc')
                ->field($filed)
                ->join('order o', 'oc.order_id=o.order_id')
                ->join('course cr', 'oc.course_id=cr.courseid')
                ->join('user u', 'u.user_id=oc.buyer_id')
                ->join('students st', 'st.uid=oc.buyer_id')
                ->join('course_students cs', 'cs.courseid=oc.course_id AND cs.uid=oc.buyer_id', 'LEFT')
                ->where($condition)
                ->order('cr.courseid DESC')
                ->limit(($p-1) * $pageSize, $pageSize)
                ->select();
        return $list;
    }

    /**
     * 获取购买某课程的学员数量
     * @param $course_id
     * @param $sid
     * @return int|string
     */
    public function getBoughtCourseUserCount($course_id, $sid){
        $condition = [
            'oc.course_id' => $course_id,
            'oc.sid' => $sid,
            'o.status' => 1
        ];
        $count = db('order_course oc')
                ->join('order o', 'oc.order_id=o.order_id')
                ->join('course cr', 'oc.course_id=cr.courseid')
                ->join('user u', 'u.user_id=oc.buyer_id')
                ->join('students st', 'st.uid=oc.buyer_id')
                ->join('course_students cs', 'cs.courseid=oc.course_id AND cs.uid=oc.buyer_id', 'LEFT')
                ->where($condition)
                ->count();
        return $count;
    }

    /**
     * 后台: 获取预览课程二维码
     * @param $sid
     * @param $course_id
     * @return array
     */
    public function getPreviewCourseQrcode($sid, $course_id){
        $host = BaseHelper::getHostBySID($sid);
        $siteUrl = Util::http_url_path($host);
        $save_path = ROOT_PATH .'public'.DS.'uploads'.DS .'course_preview'.DS.$course_id;
        if(!file_exists($save_path)){
            mkdir($save_path, 0777, true);
        }
        $course_url = $siteUrl.'/m/html/dmscommon.html?sid='.$sid.'&escape=main.detail.'.$course_id;
        $qrcode = Util::createQRcode($save_path, $course_url);
        if($qrcode){
            $qrcode_url = $siteUrl.DS.'uploads'.DS .'course_preview'.DS.$course_id.DS.'qrcode.png';
            return ['status' => 1, 'msg' => '预览成功', 'data' => ['qrcode_url' => $qrcode_url]];
        } else {
            return ['status' => 0, 'msg' => '预览失败'];
        }
    }

    /**
     * 后台: 改变课程发布状态
     * @param $sid
     * @param $course_id
     * @param $course_status
     * @return int
     */
    public function changeCourseStatus($sid, $course_id, $course_status){
        $where = [
            'courseid' => $course_id,
            'sid' => $sid,
            'course_status' => $course_status ? 0 : 1
        ];
        return db('course')->where($where)->setField('course_status', $course_status);
    }

    /**
     * 获取课程凭证二维码
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return array
     */
    public function getCourseCertificate($sid, $uid, $course_id){
        $is_buy = $this->isBuyCourse($sid, $uid, $course_id);
        if($is_buy != 1){
            return ['status' => 0, 'msg' => '请先购买此课程'];
        }

        $field = 'courseid,name,speaker,schooltime,schoolovertime';
        $course = db('course')->field($field)->where(['sid' => $sid, 'courseid' => $course_id, 'course_status' => 1])->find();
        if(!$course){
            return ['status' => 0, 'msg' => '课程信息不存在'];
        }
        $course['speaker'] = json_decode($course['speaker']);
        $course['schooltime'] = date('Y/m/d H:i', $course['schooltime']);
        $course['schoolovertime'] = date('H:i', $course['schoolovertime']);

        $host = BaseHelper::getHostBySID($sid);
        $siteUrl = Util::http_url_path($host);
        $save_path = ROOT_PATH .'public'.DS.'uploads'.DS .'course_certificate'.DS.$course_id.DS.$uid;
        if(!file_exists($save_path)){
            mkdir($save_path, 0777, true);
        }

        $qrcode_path = $save_path.DS.'qrcode.png';
        if(!file_exists($qrcode_path)){
            $course_url = $siteUrl.'/m/html/dmscommon.html?sid='.$sid.'&uid='.$uid.'&escape=main.detail.'.$course_id.'#uid='.$uid.'@courseid='.$course_id;
            $qrcode = Util::createQRcode($save_path, $course_url);
            if(!$qrcode){
                return ['status' => 0, 'msg' => '获取失败'];
            }
        }
        $course['qrcode_url'] = $siteUrl.DS.'uploads'.DS .'course_certificate'.DS.$course_id.DS.$uid.DS.'qrcode.png';
        return ['status' => 1, 'msg' => '获取成功', 'data' => $course];
    }


    /**
     * 微信端: 获取自身所有班级课程列表
     * @param $sid
     * @param $uid
     * @param $type
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getAllClassCourseList($sid, $uid, $type, $p, $pageSize){
        $condition = [
            'cs.uid' => $uid,
            'cs.sid' => $sid,
        ];
        $course_class = db('class_students cs')
                        ->field('cc.courseid')
                        ->join('course_class cc', 'cs.classid=cc.classid')
                        ->where($condition)
                        ->select();
        $course_ids = [];
        if($course_class){
            foreach($course_class as $k => $v){
                $course_ids[$k] = $v['courseid'];
            }
        }
        $course_ids = array_unique($course_ids);

        $where = [
            'courseid' => ['in', $course_ids],
            'sid' => $sid,
            'course_status' => 1
        ];

        if($type == 1){
            //未开始
            $where['schooltime'] = ['>', time()];
            $order = 'schooltime ASC';
        } elseif($type == 2){
            //进行中
            $where['schooltime'] = ['<', time()];
            $where['schoolovertime'] = ['>', time()];
            $order = 'schooltime ASC';
        } elseif($type == 3){
            //已结束
            $where['schoolovertime'] = ['<', time()];
            $order = 'schoolovertime DESC';
        }

        $filed = 'courseid,name,speaker,schooltime,schoolovertime,pic';
        $list = db('course')
                ->field($filed)
                ->where($where)
                ->limit(($p - 1)*$pageSize, $pageSize)
                ->order($order)
                ->select();

        if($list){
            foreach($list as $key => $val){
                $list[$key]['speaker'] = json_decode($val['speaker']);
                $list[$key]['schooltime'] = date('Y/m/d H:i', $val['schooltime']);
                $list[$key]['schoolovertime'] = date('H:i', $val['schoolovertime']);
            }
        }

        return $list;
    }


    /**
     * 微信端: 管理员进行购买设置
     * @param $sid
     * @param $uid
     * @param array $postParam
     * @return array
     */
    public function purchaseSettingByAdmin($sid, $uid, $postParam = [])
    {
        // 只能管理员操作
        $is_admin = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->value('is_administrator');
        if(!$is_admin){
            return ['status' => 0, 'msg' => '无操作权限'];
        }

        $course = db('course')->where(['sid' => $sid, 'courseid' => $postParam['course_id'], 'course_status' => ['<>', -1]])->find();
        if(!$course){
            return ['status' => 0, 'msg' => '课程不存在'];
        }

        // 添加关联班级
        if(is_array($postParam['class_ids']) && count($postParam['class_ids']) > 0){
            //添加课程推送模版任务
            if(!$this->isTemplateStore($sid)){
                $coursePushService = new CoursePushTplService();
                $coursePushService->addCoursePushTask($sid, $postParam['course_id'], $postParam['class_ids'], $course['course_push_tpl_id'], false, $course['using_class_setting_push']);
            }

            $courseClassService = new CourseClassService();
            $r = $courseClassService->addCourseClass($postParam['course_id'], $postParam['class_ids']);
            if($r === false){
                return ['status' => 0, 'msg' => '关联班级失败'];
            }
        }

        // 购买设置
        return $this->buySetting($sid, $postParam);
    }


    /**
     * 获取课程关联的班级
     * @param $sid
     * @param $uid
     * @param $course_id
     * @return mixed
     */
    public function getRelateClass($sid, $course_id)
    {
        $field = 'cl.classid,cl.name';
        $where = [
            'c.sid' => $sid,
            'c.courseid' => $course_id,
            'c.course_status' => ['<>', -1],
            'cl.status' => ['<>', -1]
        ];
        $list = db('course c')
                ->field($field)
                ->join('course_class cc', 'c.courseid=cc.courseid')
                ->join('classes cl', 'cl.classid=cc.classid')
                ->where($where)
                ->select();
        return $list;
    }
}






















